package com.society.sgsc.dict.handler;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.society.sgsc.dict.service.DictItemService;
import com.society.sgsc.entities.DictItem;
import com.society.sgsc.utils.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * 字典详情模块
 */

@RequestMapping("dictItem")
@RestController
@CrossOrigin
@Slf4j
public class DictItemHandler {

    @Resource
    DictItemService dictItemService;

    @PostMapping("addDictItem")
    public CommonResult<DictItem> addDictItem(@RequestBody DictItem dictItem)  {

        try {
            int i = dictItemService.saveDictItem(dictItem);
            //进行判断
            if(1 == i){
                return CommonResult.success(dictItem);
            }else {
                return CommonResult.error(201,"添加失败，添加用户已存在，请重试");
            }
        }catch (Exception e) {
            e.printStackTrace();
            return  CommonResult.error(500,"系统异常,请重试或联系管理员"+e.getMessage());
        }

    }

    @GetMapping("/page/{dictType}/{pn}/{size}")
    public CommonResult dictItemByDictType(@PathVariable("dictType") String dictType, @PathVariable("pn") Integer pn, @PathVariable("size") Integer size) {
        PageInfo<DictItem> pageInfo = null;
       try {
           PageHelper.startPage(pn, size);//对查询的数据进行分页
           QueryWrapper<DictItem> wrapper = new QueryWrapper<>();
           wrapper.eq("dict_type", dictType);
           List<DictItem> list = dictItemService.list(wrapper);
           if(null == list || list.size() == 0){
               return CommonResult.error(204,"查询成功，暂无数据");
           }
           //如果不为空就将获取到的集合输出出去
           pageInfo = new PageInfo<>(list);
           return CommonResult.success(pageInfo);
       }catch (Exception e) {
           e.printStackTrace();
            return CommonResult.error(500,"系统错误，请重试或联系管理员"+e.getMessage());
       }
    }

}
